<template>
  <el-dialog
    @close="close"
    title="添加&修改礼物信息"
    :visible.sync="dialog"
    width="45%"
  >
    <el-form size="mini" :model="formInline" :rules="rules" ref="formInline" label-width="100px">
      <el-form-item label="礼物名称：" prop="prizename" >
        <el-input v-model="formInline.prizename"></el-input>
      </el-form-item>
      <el-form-item prop="photo" label="礼物图片：">
        <input accept="image/gif, image/jpeg, image/png" class="upload-file_ipt" @change="tirggerFile($event)" type="file" >
        <br>
        <img  width="68" height="68" :src="showImg" alt="">
      </el-form-item>
      <el-form-item label="礼物价格：" >
       <!-- <el-input v-model="formInline.pricecoin" class="gift_inpus"></el-input>N币-->
        <el-input v-model="formInline.pricebean" class="gift_inpus"></el-input>N豆
      </el-form-item>
      <el-form-item label="礼物贡献值：" prop="title" >
        <el-input placeholder="请输入该礼物的贡献值" v-model="formInline.attribute"></el-input>
      </el-form-item>
      <el-form-item label="礼物魅力值：" prop="title" >
        <el-input placeholder="请输入该礼物的魅力值" v-model="formInline.charm"></el-input>
      </el-form-item>
      <el-form-item label="单个礼物特效：" prop="title" >
          <el-upload
            class="upload-demo"
            ref="upload"
            name="filename"
            :on-success="effecturlSuccess"
            :action=incrementURL
            :headers=token
            :limit="1"
            :on-change="changeFilelist"
            :on-remove="handleRemove"
            :file-list="fileList"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">点击上传素材包</el-button>
            <!--<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
           <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
          </el-upload>
      </el-form-item>
      <el-form-item label="触发特效数量：" prop="effectnum" >
        <el-input class="gift_inpuss" placeholder="赠送多少个触发大礼物特效" v-model="formInline.triggernum" ></el-input>个
      </el-form-item>
      <el-form-item label="多个礼物特效：" prop="title" >
          <el-upload
            class="upload-demo"
            ref="upload2"
            name="filename"
            :limit="1"
            :on-change="changeMoreFilelist"
            :on-success="effectmoreurlSuccess"
            :action=incrementURL
            :headers=token
            :on-remove="handleMoreRemove"
            :file-list="moreFileList"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">点击上传素材包</el-button><span style="color: #999999">(比如，赠送99个该礼物触发的特效)</span>
           <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
           <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
          </el-upload>
      </el-form-item>
      <el-form-item label="赠送数量选项：">
       <!-- <el-radio v-model="formInline.givenum" label="1" border>1</el-radio>
        <el-radio v-model="formInline.givenum" label="10" border>10</el-radio>
        <el-radio v-model="formInline.givenum" label="66" border>66</el-radio>
        <el-radio v-model="formInline.givenum" label="188" border>188</el-radio>-->
        <el-input style="width: 50px" v-model="giveNumObject.attribute1"></el-input>
        <el-input style="width: 50px" v-model="giveNumObject.attribute2"></el-input>
        <el-input style="width: 50px" v-model="giveNumObject.attribute3"></el-input>
        <el-input style="width: 50px" v-model="giveNumObject.attribute4"></el-input>
      </el-form-item>
      <el-form-item prop="status" label="礼物状态">
        <el-radio v-model="formInline.status"  :label="0">已上架</el-radio>
        <el-radio v-model="formInline.status" :label="1">未上架</el-radio>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :disabled="btnLoading" @click="dialog = false">取 消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>

</template>
<script>
  import { addGiftSystemAPI , obtainedGiftSystemAPI , getGiftDetailAPI} from '@/api/gift'
  import { upload } from '@/utils/other-request'
  import { mapGetters } from 'vuex'
  import { getToken } from '@/utils/auth' // get token from cookie

  export default {
    name: 'GiftListEdit',
    props: {
      dialog_: {
        type: Boolean,
        default: false
      },
      id: {
        type: Number,
        default: null
      }
    },
    data() {
      var validateSort = (rule, value, callback) => {``
        var reg = /^[0-9]\d*$/
        if (value === null || value === '' | value === undefined) {
          callback()
        } else if (!reg.test(value)) {
          return callback(new Error('请输入正确的数字'))
        } else {
          callback()
        }
      }
      return {
        props: {
          label: 'title',
          children: 'children'
        },
        token:'',
        incrementURL:process.env.VUE_APP_BASE_API + '/admin/admin/uploadeffectfile', // 特效文件上传action
        fileList:[],
        moreFileList:[],
        isFilelist:false,
        isMoreFilelist:false,
        isDelete:false, // 是否执行了删除操作
        options: [{
          value: 'PC客户端',
          label: 'PC客户端'
        }, {
          value: 'PCweb客户端',
          label: 'PCweb客户端'
        }],
        value: '',
        dialog: false,
        showImg: null,
        formInline: {
          id: 0,
          photo:'',
          status: 1,
          givenum : '',
          effecttype:'',
          effecturl:'',//单个礼物特效
          effectmoreurl:'' ,// 多个礼物特效


        },
        btnLoading: false,
        giveNumObject:{
          attribute1:'',
          attribute2:'',
          attribute3:'',
          attribute4:''
        },
        givenumArray:[],
        treeData: [],
        rules: {
          name: [
            { required: true, message: '请填写角色名称', trigger: 'blur' }
          ],
          remark: [
            { required: true, message: '请填写角色描述', trigger: 'blur' }
          ],
          sort: [
            { validator: validateSort, trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'img_base_url',
      ])
    },
    methods: {
      // 选择头像回调
      tirggerFile(event) {
        var e = event || window.event;
        this.formInline.photo = e.target.files[0]
        this.showImg = URL.createObjectURL(this.formInline.photo)
      },
      // 根据ID查询详情
      getDetails() {
          getGiftDetailAPI({ id: this.id }).then(res => {
            if (res.code === 0) {
              this.formInline = res.data
              this.givenumArray = res.data.givenum.split(",")
              this.giveNumObject.attribute1 = this.givenumArray[0]
              this.giveNumObject.attribute2 = this.givenumArray[1]
              this.giveNumObject.attribute3 = this.givenumArray[2]
              this.giveNumObject.attribute4 = this.givenumArray[3]
              this.showImg = this.img_base_url + this.formInline.photo
              // 回显已经上传成功的文件名
              let effecturl = '';
              let effectmoreurl = '';
              let effecturlIndex = res.data.effecturl.lastIndexOf("/")
              if(effecturlIndex > 0){
                 effecturl = res.data.effecturl.substring(effecturlIndex+1,res.data.effecturl.length)
                this.fileList = [{name:effecturl,url:res.data.effecturl}]
              }
              let effectmoreurlIndex = res.data.effectmoreurl.lastIndexOf("/")
              if(effectmoreurlIndex > 0){
                 effectmoreurl = res.data.effectmoreurl.substring(effectmoreurlIndex+1,res.data.effectmoreurl.length)
                this.moreFileList = [{name:effectmoreurl,url:res.data.effectmoreurl}]
              }
            } else {
              this.$message.error("查询失败")
            }
          })
      },
      handleRemove(file, fileList) {
        this.isFilelist = false
        this.$refs.upload.clearFiles();
        this.isDelete = true;
      },
      handleMoreRemove(){
        this.formInline.effectmoreurl = "null";
        this.$refs.upload2.clearFiles();
      },
      handlePreview(file) {
        console.log(file);
      },
      effecturlSuccess(response, file, fileList){
        if(response.code == 0){
          this.formInline.effecturl = response.data.path
          if(this.isMoreFilelist){ // 如果多个特效礼物上传成功
            this.$refs.upload2.submit();
          }else{  // 如果多个礼物输入框没有上传
            this.commonAddOrUpdate();
          }
        }
      },
      effectmoreurlSuccess(response, file, fileList){
        if(response.code == 0){ // 如果单个礼物特效上传成功
            this.formInline.effectmoreurl = response.data.path
            this.commonAddOrUpdate();

        }
      },
      // 单个特效上传change事件
      changeFilelist(file, fileList){
        if(file != null && file != undefined){
          this.isFilelist = true
        }else{
          this.isFilelist = false
        }
      },
      // 多特效上传change事件
      changeMoreFilelist(file, fileList){
        if(file != null && file != undefined){
          this.isMoreFilelist = true
        }else{
          this.isMoreFilelist = false
        }
      },
      close() {
        this.$emit('close')
      },
      addSubmit() {
        addGiftSystemAPI(this.formInline).then(res => {
          this.btnLoading = false
          if (res.code === 0) {
            this.$message.success('操作成功')
            this.$emit('success')
            this.dialog = false
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      updateSubmit() {
        obtainedGiftSystemAPI(this.formInline).then(res => {
          this.btnLoading = false
          if (res.code === 0) {
            this.$message.success(res.msg)
            this.$emit('success')
            this.dialog = false
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      // 公共的上传方法
      commonAddOrUpdate(){
        if (this.id) { // 编辑
          if(this.isDelete){ // 如果点击了单礼物特效文件删除操作
            if(!this.isFilelist){
              this.$message.error("单个礼物特效不能为空!!!")
              return
            }
          }
          this.btnLoading = true
          if (typeof this.formInline.photo === 'string') {
            this.updateSubmit()
          } else {
            let formData = new FormData()
            formData.append("filename", this.formInline.photo)
            upload(formData).then(res => {
              this.formInline.photo = res.data.path
              this.updateSubmit()
            })
          }
        } else { // 增加
          if(!this.isFilelist){ // 增加的情况下，如果单特效为false（空）
            this.$message.error("单个礼物特效不能为空!!!")
            return
          }
          this.btnLoading = true
          let formData = new FormData()
          formData.append("filename", this.formInline.photo)
          upload(formData).then(res => {
            this.formInline.photo = res.data.path
            this.addSubmit()
          })
        }
      },
      // 提交
      onSubmit() {
        this.$refs.formInline.validate((valid) => {
          if (valid) {
            if(this.giveNumObject.attribute1 == '' || this.giveNumObject.attribute2 == '' || this.giveNumObject.attribute3 == '' || this.giveNumObject.attribute4 == ''){
              this.$message.error("赠送礼物选项四项必填!!!")
              return false;
            }
            this.formInline.givenum = this.giveNumObject.attribute1 + ',' + this.giveNumObject.attribute2 + ',' + this.giveNumObject.attribute3 + ','+ this.giveNumObject.attribute4
            if(this.isFilelist){ // 如果上传了单礼物特效
              this.$refs.upload.submit();
            }else if(this.isMoreFilelist){ // 如果编辑的时候仅仅修改了多礼物特效
              this.$refs.upload2.submit();
            }else {
              this.commonAddOrUpdate();
            }
           /*if(this.id){
              this.btnLoading = true
              obtainedGiftSystemAPI(this.formInline).then(res => {
                this.btnLoading = false
                if (res.code === 0) {
                  this.$message.success('操作成功')
                  this.$emit('success')
                  this.dialog = false
                } else {
                  this.$message.error(res.message)
                }
              })
            }else{
              this.btnLoading = true
              addGiftSystemAPI(this.formInline).then(res => {
                this.btnLoading = false
                if (res.code === 0) {
                  this.$message.success('操作成功')
                  this.$emit('success')
                  this.dialog = false
                } else {
                  this.$message.error(res.message)
                }
              })
            }*/

          } else {
            this.$message.warning("请填写完整的信息")
            return false;
          }
        });
        },
    },
    mounted() {
      this.token={token:getToken()}
      this.dialog = this.dialog_
      if (this.id) {
        this.getDetails() // 编辑查询详情
      } else {
        //this.getRouterAll() //新增查询菜单树信息
      }
    }
  }
</script>
<style>
  .gift_inpus{
    width:92%;
    margin-bottom:10px;
  }
  .gift_inpuss{
    width:82%;
    margin-bottom:10px;
  }
  .add_sel{
    display: inline-block;
    width:80px;
    height:30px;
    line-height: 30px;
    text-align: center;
    border: 1px solid lightgrey;
    margin-right: 10px;
    border-radius: 4px;
  }
</style>
